import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, LessThan } from 'typeorm';
import { OperationLog } from '../modules/operation-log/entities/operation-log.entity';

@Injectable()
export class LogCleanupService {
  private readonly logger = new Logger(LogCleanupService.name);

  constructor(
    @InjectRepository(OperationLog)
    private readonly operationLogRepository: Repository<OperationLog>,
  ) {}

  // 每天凌晨3点执行清理
  @Cron(CronExpression.EVERY_DAY_AT_3AM)
  async cleanupOldLogs() {
    try {
      // 删除30天前的日志
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

      const result = await this.operationLogRepository.delete({
        createdAt: LessThan(thirtyDaysAgo),
      });

      this.logger.log(`Cleaned up ${result.affected} old log entries`);
    } catch (error) {
      this.logger.error('Failed to cleanup old logs:', error);
    }
  }
}